package com.simple.modules.sys.controller;

import cn.hutool.core.date.DateUtil;
import com.simple.common.utils.EncryptUtil;
import com.simple.common.utils.R;
import com.simple.modules.sys.entity.SysUserEntity;
import com.simple.modules.sys.entity.SysUserTokenEntity;
import com.simple.modules.sys.form.SysLoginForm;
import com.simple.modules.sys.service.SysCaptchaService;
import com.simple.modules.sys.service.SysUserService;
import com.simple.modules.sys.service.SysUserTokenService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 登录相关
 *
 *
 */
@RestController
@RequestMapping("/sys/sysLogin")
public class SysLoginController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysCaptchaService sysCaptchaService;

    /**
     * 验证码
     */
    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }


    /**
     * 登录
     */
    @PostMapping("/login")
    public R login(@RequestBody SysLoginForm form){
//        boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
//        if (!captcha) {
//            return R.error("验证码不正确");
//        }

        //用户信息
        SysUserEntity user = sysUserService.queryByUserName(form.getUserName());
        if (user == null){
            return R.error("用户不存在");
        }
        //账号锁定
        if (user.getStatus() == 0) {
            return R.error("账号已被锁定,请联系管理员");
        }
        if (!user.getPassword().equals(new Sha256Hash(EncryptUtil.decode(form.getPassword()), user.getSalt()).toHex())) {
            //账号不存在、密码错误
            sysUserService.updateUserStatusByLoginTime(user.getUserId(),0);
            return R.error("密码不正确");
        }

        R r = new R();
        if (user.getPasswordUpdateTime() == null || DateUtil.betweenDay(user.getPasswordUpdateTime(),new Date(),true) >= 180){
            r.put("code",206);
        }
        sysUserService.updateUserStatusByLoginTime(user.getUserId(),1);
        //生成token，并保存到数据库
        Map<String, Object> tokenMap = sysUserTokenService.createToken(user.getUserId());
        r.putAll(tokenMap);
        return r;
    }


    /**
     * 退出
     */
    @PostMapping("/logout")
    public R logout() {
        sysUserTokenService.logout(getUserId());
        return R.ok();
    }

    /**
     * 供其他系统调用
     * @param token
     * @return
     */
    @GetMapping("/checkToken")
    public R checkToken(@RequestParam("token")String token){
        SysUserTokenEntity tokenEntity = sysUserTokenService.getOneByToken(token);
        //token失效
        if(tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            return R.ok().put("flag",false);
        }else {
            return R.ok().put("flag",true);
        }
    }
}
